import { useEffect, useState } from "react";
import { Button, Card, Drawer, Form, Input, Space, Select, Spin } from "antd";
import type { ColumnsType } from "antd/es/table";
import programService, { type PageListReq } from "@/api/services/eam/maintailProgramService";
import type { EamEquipmentMaintainProgram } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
import CustomTable from "@/components/grid/CustomTable";

const { TextArea } = Input;

export default function EamEquipmentMaintainProgramPage() {
	const [loading, setLoading] = useState(false);
	const [submitLoading, setSubmitLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		name: undefined,
		type: undefined,
		periodType: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<EamEquipmentMaintainProgram[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<EamEquipmentMaintainProgram | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 405;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const typeOptions = useDictionary("equipment_maintain_program_type");
	const periodTypeOptions = useDictionary("period_type");

	const columns: ColumnsType<EamEquipmentMaintainProgram> = [
		{
			title: "项目名称",
			width: 120,
			key: "name",
			dataIndex: "name",
		},
		{
			title: "项目类型",
			width: 120,
			key: "type",
			dataIndex: "type",
			align: "center",
			render: (_, record) => <TableDictTag dictCode="equipment_maintain_program_type" value={record.type ?? ""} />,
		},
		{
			title: "周期类型",
			width: 120,
			key: "periodType",
			dataIndex: "periodType",
			align: "center",
			render: (_, record) => <TableDictTag dictCode="period_type" value={record.periodType ?? ""} />,
		},
		{
			title: "方法",
			width: 120,
			key: "method",
			dataIndex: "method",
		},
		{
			title: "耗材",
			width: 120,
			key: "consumable",
			dataIndex: "consumable",
		},
		{
			title: "工具",
			width: 120,
			key: "tool",
			dataIndex: "tool",
		},
		{
			title: "标准",
			width: 120,
			key: "standard",
			dataIndex: "standard",
		},
		{
			title: "最大值",
			width: 120,
			key: "maxValue",
			dataIndex: "maxValue",
		},
		{
			title: "最小值",
			width: 120,
			key: "minValue",
			dataIndex: "minValue",
		},
		{
			title: "单位",
			width: 120,
			key: "unit",
			dataIndex: "unit",
		},
		{
			title: "备注",
			width: 120,
			key: "remark",
			dataIndex: "remark",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		programService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (eamEquipmentMaintainProgram: EamEquipmentMaintainProgram) => {
		setEditingData(eamEquipmentMaintainProgram);
		form.setFieldsValue(eamEquipmentMaintainProgram);
		setDrawerVisible(true);
		setIsView(false);
	};

	//触发视图按钮
	const handleView = (eamEquipmentMaintainProgram: EamEquipmentMaintainProgram) => {
		setEditingData(eamEquipmentMaintainProgram);
		form.setFieldsValue(eamEquipmentMaintainProgram);
		setIsView(true);
		setDrawerVisible(true);
	};

	//提交表单数据
	const handleSubmit = async (values: EamEquipmentMaintainProgram) => {
		try {
			setSubmitLoading(true);

			const data = {
				...values,
				id: editingData?.id,
			};
			if (editingData) {
				await programService.update(data);
				toast.success("更新点检保养项目成功");
			} else {
				await programService.add(data);
				toast.success("创建点检保养项目成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(`保存失败: ${error.message}`);
		} finally {
			setSubmitLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await programService.remove(selectedRowKeys);
			toast.success("删除点检保养项目成功");
			setSelectedRowKeys([]);
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	return (
		<Spin spinning={submitLoading} tip="数据提交中..." size="large">
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="name" label="项目名称">
						<Input allowClear placeholder="请输入项目名称" />
					</Form.Item>

					<Form.Item name="type" label="项目类型">
						<Select options={typeOptions} allowClear style={{ width: 170 }} placeholder="请选择项目类型" />
					</Form.Item>

					<Form.Item name="periodType" label="周期类型">
						<Select options={periodTypeOptions} allowClear style={{ width: 170 }} placeholder="请选择周期类型" />
					</Form.Item>

					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<CustomTable
					loading={loading}
					columnsConfig={columns}
					dataSource={list}
					total={total}
					selectedRowKeys={selectedRowKeys}
					setSelectedRowKeys={setSelectedRowKeys}
					current={queryParams.page}
					pageSize={queryParams.pageSize}
					onRefresh={fetchPageList}
					onPageChange={handlePageChange}
					selectable
					toolbarButtons={
						<>
							<Button type="primary" onClick={handleAdd}>
								新增
							</Button>
							<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
								删除
							</Button>
						</>
					}
					scroll={{ y: tableScrollY }}
				/>
			</Card>
			<Drawer
				title={editingData ? "编辑点检保养项目" : "新增点检保养项目"}
				width={600}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" loading={submitLoading} onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Form.Item
						name="name"
						label="项目名称"
						rules={[
							{
								required: true,
								message: "请填写项目名称",
							},
						]}
					>
						<Input placeholder="请输入项目名称" allowClear />
					</Form.Item>

					<Form.Item
						name="type"
						label="项目类型"
						rules={[
							{
								required: true,
								message: "请填写项目类型",
							},
						]}
					>
						<Select options={typeOptions} allowClear />
					</Form.Item>

					<Form.Item
						name="periodType"
						label="周期类型"
						rules={[
							{
								required: true,
								message: "请填写周期类型",
							},
						]}
					>
						<Select options={periodTypeOptions} allowClear />
					</Form.Item>

					<Form.Item name="method" label="方法">
						<Input placeholder="请输入方法" allowClear />
					</Form.Item>

					<Form.Item name="consumable" label="耗材">
						<Input placeholder="请输入耗材" allowClear />
					</Form.Item>

					<Form.Item name="tool" label="工具">
						<Input placeholder="请输入工具" allowClear />
					</Form.Item>

					<Form.Item name="standard" label="标准">
						<Input placeholder="请输入标准" allowClear />
					</Form.Item>

					<Form.Item name="maxValue" label="最大值">
						<Input placeholder="请输入最大值" allowClear />
					</Form.Item>

					<Form.Item name="minValue" label="最小值">
						<Input placeholder="请输入最小值" allowClear />
					</Form.Item>

					<Form.Item name="unit" label="单位">
						<Input placeholder="请输入单位" allowClear />
					</Form.Item>

					<Form.Item name="remark" label="备注">
						<TextArea />
					</Form.Item>
				</Form>
			</Drawer>
		</Spin>
	);
}
